import {Component} from 'react'
import {
  Button,
  Card,
  Checkbox,
  Form,
  Input, message
} from "antd";
import 'pages/Login/index.scss'
import Logo from 'assets/logo.png'
import {login} from "api/user";
import {setToken} from "utils/local";

class Login extends Component {

  handleLogin = async (values) => {
    // 获取跳转前传递的路由参数
    const fromPathName = this.props.location?.state?.fromPath // undefined
    try {
      // 登录，调用我们的login方法
      const res = await login(values)
      // 存储token
      // setToken(res.data.token)
      setToken(res.data.token)
      // 成功地提示
      message.success('登录成功')
      // history.push('路径')

      this.props.history.push(fromPathName || '/home')
      // console.log(values)
    } catch (e) {
      message.error('登录失败')
    }
  }

  render() {
    return <div className="login">
      <Card className={'loginContainer'}>
        <img className="loginLogo" src={Logo} alt=""/>
        {/*  构建一个表单结构*/}
        <Form
          size={'large'}
          validateTrigger={['onChange', 'onBlur']}
          // 表单的提交事件
          onFinish={this.handleLogin}
          name={'basic'}
          // 表单的默认值
          initialValues={{
            mobile: '13811111111',
            code: '246810',
            remember: true
          }}
        >
          <Form.Item
            rules={[
              {
                pattern: /^\d{11}$/,
                message: '手机号格式不正确'
              },
              {
                required: true,
                message: '手机号不能为空'
              }
            ]}
            name={'mobile'}
          >
            <Input
              placeholder={'请输入手机号'}
            />
          </Form.Item>
          <Form.Item
            id={'code'}
            name={'code'}
            rules={[
              {
                pattern: /^\d{6}$/,
                message: '验证码不符合规则'
              },
              {
                required: true,
                message: '验证码不能为空'
              }
            ]}
          >
            <Input placeholder={'请输入密码'}/>
          </Form.Item>
          <Form.Item
            name={'remember'}
            valuePropName={'checked'}
            rules={[
              {
                validator(_, value) {
                  // 返回了一个reject状态的promise，表单校验失败
                  // 返回了一个resolve状态的promise,表单校验成功
                  return value ? Promise.resolve() : Promise.reject(new Error('请阅读协议'))
                }
              }
            ]}
          >
            <Checkbox>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
          </Form.Item>
          <Form.Item>
            <Button
              htmlType={'submit'}
              type={'primary'}
              block
            >登录</Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  }
}

export default Login

